<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="50%"
    @open="openDialog"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      label-position="top"
      class="menu-dialog"
    >
      <el-form-item label="菜单类型" prop="menuType">
        <el-radio-group v-model="form.menuType">
          <el-radio label="1">系统</el-radio>
          <el-radio label="2">菜单</el-radio>
          <el-radio label="3">按钮</el-radio>
          <el-radio label="4">字段</el-radio>
          <el-radio label="5">页面</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上级页面">
        <el-select
          ref="select"
          v-model="selectLabel"
          clearable
          placeholder="请选择上级页面,不选择则在根目录创建"
          @clear="selectClear"
        >
          <el-option :value="form.parentId" style="height: unset">
            <el-tree
              :data="props.treeData"
              v-bind="tree"
              @node-click="handleNodeClick"
            />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item prop="component" label="前端组件:">
        <el-input v-model="form.component" />
      </el-form-item>
      <el-form-item prop="status" label="状态:">
        <el-switch
          v-model="form.status"
          active-color="#13ce66"
          :active-text="['禁用', '启用'][form.status]"
          inactive-color="#ff4949"
        />
      </el-form-item>
      <el-form-item prop="sort" label="排序:">
        <el-input v-model.number="form.sort" />
      </el-form-item>
      <el-form-item
        v-for="(item, idx) in form.url"
        :key="idx"
        :rules="{
          required: true,
          message: `请输入权限标识${idx + 1}`,
          trigger: 'blur',
        }"
        :prop="`url.${idx}.value`"
        :label="`权限地址${idx + 1}:`"
      >
        <el-input v-model="item.value" style="width: 65%; margin-right: 10px" />
        <div style="display: inline-block">
          <el-button
            :icon="Plus"
            round
            plain
            type="primary"
            size="small"
            @click.prevent="addUrl(idx)"
            >新增</el-button
          >
          <el-button
            v-if="form.url.length > 1"
            :icon="Delete"
            round
            plain
            type="danger"
            size="small"
            @click.prevent="deleteUrl(idx)"
          />
        </div>
      </el-form-item>
      <el-form-item
        v-if="form.menuType == 1 || form.menuType == 2"
        prop="icon"
        label="图标:"
      >
        <!-- <el-input v-model="form.icon" /> -->
        <IconSelect v-model="form.icon" />
      </el-form-item>
      <el-form-item>
        <div class="from-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确认</el-button
          >
        </div>
      </el-form-item>
    </el-form>
    <!-- <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确认</el-button>
      </span>
    </template> -->
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, getCurrentInstance, toRef } from 'vue';
import { Delete, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { internetApi } from '@/api/api.js';
import IconSelect from './iconSelect.vue';
const currentInstance = getCurrentInstance();
const { $request } = currentInstance.appContext.config.globalProperties;

const ruleFormRef = ref();
const dialogVisible = ref(false);
const dialogTitle = ref(''); //弹窗标题
const selectLabel = ref(''); //select展示选中的上级名称
const select = ref(null);
const form = reactive({
  id: null,
  menuType: '1',
  parentId: '0',
  name: '',
  component: '',
  sort: null,
  icon: null,
  status: true,
  url: null,
});
const tree = reactive({
  props: {
    children: 'children',
    label: 'name',
  },
  expandOnClickNode: false,
  nodeKey: 'id',
});
const props = defineProps({
  treeData: {
    type: Array,
    default: () => [],
  },
  treeList: {
    type: Array,
    default: () => [],
  },
  getMenuList: Function,
});
const rules = reactive({
  menuType: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  name: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '2-20个字之间', trigger: 'blur' },
  ],
  component: [
    { required: true, message: '唯一编码不能为空', trigger: 'blur' },
    { max: 200, message: '200个字以内', trigger: 'blur' },
  ],
  sort: [
    { required: true, message: '排序不能为空', trigger: 'blur' },
    {
      type: 'number',
      min: 1,
      max: 127,
      message: '请输入1-127之间的数字',
      trigger: 'blur',
    },
  ],
  icon: [
    { required: true, message: '图标不能为空', trigger: 'blur' },
    { max: 50, message: '50个字以内', trigger: 'blur' },
  ],
});

// 权限地址：编辑格式处理
const strToArr = (data, first) => {
  const ds = data.split(',') || [];
  const newArr = ds.map((item) => {
    return {
      value: item,
    };
  });
  if (first) {
    return newArr[0].value;
  } else {
    // newArr.shift()
    return newArr;
  }
};
const arrToStr = (array) => {
  let str = '';
  array.forEach((el) => {
    str += el.value + ',';
  });
  if (str) {
    return str.substring(0, str.length - 1);
  }
  return '';
};
// 打开弹窗，父组件调用的方法，且弹窗方法
const openDialog = (row, type) => {
  if (type == 'add') {
    dialogTitle.value = '新建菜单';
    form.id = null;
    form.parentId = row.id || '0';
    form.name = null;
    form.component = null;
    form.menuType = '1';
    form.status = true;
    form.url = [{ value: '' }];
    form.sort = null;
    form.icon = null;
    selectLabel.value = row.name || '';
  } else if (type == 'edit') {
    dialogTitle.value = '编辑菜单';
    form.id = row.id;
    form.parentId = row.parentId;
    form.name = row.name;
    form.component = row.component;
    form.menuType = row.menuType;
    form.status = row.status;
    form.url = strToArr(row.url);
    form.sort = row.sort;
    form.icon = row.icon;
    const tmp = props.treeList.filter((item) => {
      return item.id === row.parentId;
    });
    selectLabel.value = tmp.length ? tmp[0].name : '';
  }
  dialogVisible.value = true;
  console.log('row', row);
  // console.log('type',type)
};
//清空单选框时
const selectClear = () => {
  form.parentId = '0';
  selectLabel.value = '';
};
//树节点点击
const handleNodeClick = (data) => {
  // selese组件不会主动收缩起来，需要手动操作
  nextTick(() => {
    select.value.blur();
  });
  selectLabel.value = data.name;
  form.parentId = data.id;
};
// 新增权限地址
const addUrl = (idx) => {
  form.url.splice(idx + 1, 0, { value: '' });
};
// 删除权限地址
const deleteUrl = (idx) => {
  form.url.splice(idx, 1);
};
// 确认添加菜单
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const model = Object.assign({}, form);
      model.url = arrToStr(form.url);
      if (form.id) {
        $request(internetApi.updateMenu, model);
      } else {
        $request(internetApi.addMenu, model);
      }
      ElMessage({
        message: '操作成功',
        type: 'success',
      });
      dialogVisible.value = false;
      setTimeout(() => {
        console.log(
          '2------------------------------------>',
          props.getMenuList()
        );
        props.getMenuList();
      }, 500);
      console.log('submit!');
    } else {
      console.log('error submit!', fields);
    }
  });
};
//测试所用
const fn = () => {
  console.log('执行了fn');
};
// 导出，使父组件可调用子组件的方法或者值
defineExpose({
  fn,
  openDialog,
});
</script>
<style lang="scss" scoped>
.from-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.menu-dialog {
  .el-select {
    width: 100%;
  }
}
</style>
